package com.example.demo.demos.web.util;

import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;

import java.io.FileOutputStream;
import java.io.OutputStream;

public class PdfGenerator {
    public static void generatePdf(String html, String outputPath) throws Exception {
        try (OutputStream os = new FileOutputStream(outputPath)) {
            PdfRendererBuilder builder = new PdfRendererBuilder();
            builder.useFastMode();
            builder.withHtmlContent(html, null);
            builder.toStream(os);

            // 注册支持中文的字体（注意路径）
            builder.useFont(
                    () -> PdfGenerator.class.getClassLoader().getResourceAsStream("fonts/NotoSansSC-Regular.ttf"),
                    "Noto Sans SC"
            );

            // 指定字体作为默认字体，避免中文乱码
            builder.useDefaultPageSize(210, 297, PdfRendererBuilder.PageSizeUnits.MM);
            builder.run();
        }
    }
}

